package bTree.LeetCode;

public class 岛屿的最大面积 {
    int[][] dir = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
    int max = 0;

    public int maxAreaOfIsland(int[][] grid) {
        int row = grid.length;
        int line = grid[0].length;
        boolean[][] visited = new boolean[row][line];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < line; j++) {
                if (grid[i][j] == 1 && !visited[i][j]) {
                    int temp = 0;
                    dfs(i, j, grid, visited, temp);
                }
            }
        }
        return max;
    }

    private void dfs(int x, int y, int[][] grid, boolean[][] visited, int temp) {
        if (grid[x][y] == 0) {
            return;
        }
        visited[x][y] = true;
        temp++;
        if (temp > max) {
            max = temp;
        }
        for (int i = 0; i < 4; i++) {
            int nextX = x + dir[i][0];
            int nextY = x + dir[i][1];
            if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length || visited[nextX][nextY]) {
                continue;
            }
            dfs(nextX, nextY, grid, visited, temp);
        }
    }
}